<template>
  <div class="container">
    <h1 class="mb-4">投资历史版本</h1>
    
    <!-- 加载中提示 -->
    <div v-if="loading">
      <loading-spinner size="large" message="加载历史数据..." />
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="alert alert-danger mb-4">
      {{ error }}
    </div>
    
    <div v-if="!loading" class="card mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="mb-0">数据哈希信息</h3>
        <hash-display :value="dataHash" :shorten="false" />
      </div>
      <div class="card-body">
        <p class="mb-3">
          <i class="bi bi-info-circle me-2"></i>
          数据哈希是投资数据的唯一标识，每次更新投资记录时，都会生成新的数据哈希，并在链上记录历史版本。
        </p>
        
        <div class="alert alert-secondary" v-if="historyCount === 0">
          <i class="bi bi-exclamation-triangle me-2"></i>
          未找到该数据哈希对应的历史记录
        </div>
        
        <div v-else>
          <p>
            <strong>历史版本数量:</strong> {{ historyCount }}
          </p>
          
          <div class="d-flex mb-3">
            <button 
              class="btn btn-sm btn-outline-primary me-2" 
              @click="loadPreviousVersion" 
              :disabled="currentVersionIndex <= 0"
            >
              <i class="bi bi-chevron-left"></i> 上一版本
            </button>
            <div class="flex-grow-1 text-center">
              <span class="badge bg-primary">
                版本 {{ currentVersionIndex + 1 }} / {{ historyCount }}
              </span>
            </div>
            <button 
              class="btn btn-sm btn-outline-primary ms-2" 
              @click="loadNextVersion" 
              :disabled="currentVersionIndex >= historyCount - 1"
            >
              下一版本 <i class="bi bi-chevron-right"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 历史版本展示 -->
    <div v-if="currentVersion" class="card">
      <div class="card-header">
        <h3 class="mb-0">投资版本详情</h3>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-striped">
            <tbody>
              <tr>
                <th width="30%">投资ID</th>
                <td>{{ currentVersion.id }}</td>
              </tr>
              <tr>
                <th>投资者地址</th>
                <td>
                  <hash-display :value="currentVersion.investor" :shorten="true" />
                </td>
              </tr>
              <tr>
                <th>投资金额</th>
                <td>{{ currentVersion.amount }}</td>
              </tr>
              <tr>
                <th>项目名称</th>
                <td>{{ currentVersion.projectName }}</td>
              </tr>
              <tr>
                <th>行业</th>
                <td>{{ currentVersion.profession }}</td>
              </tr>
              <tr>
                <th>交易哈希</th>
                <td>
                  <hash-display :value="currentVersion.txHash" :shorten="true" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div class="mt-4">
          <router-link :to="`/detail/${currentVersion.id}`" class="btn btn-primary me-2">
            <i class="bi bi-eye"></i> 查看当前版本
          </router-link>
          <router-link to="/" class="btn btn-secondary">
            <i class="bi bi-arrow-left"></i> 返回首页
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import LoadingSpinner from '@/components/LoadingSpinner.vue';
import HashDisplay from '@/components/HashDisplay.vue';

export default {
  name: 'HistoryView',
  components: {
    LoadingSpinner,
    HashDisplay
  },
  props: {
    dataHash: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const store = useStore();
    const route = useRoute();
    
    // 响应式数据
    const historyCount = ref(0);
    const currentVersionIndex = ref(0);
    const currentVersion = ref(null);
    
    // 状态
    const loading = computed(() => store.getters.isLoading);
    const error = computed(() => store.getters.errorMessage);
    
    // 获取历史记录数量
    const fetchHistoryCount = async () => {
      // 预处理数据哈希，确保格式正确
      let processedHash = props.dataHash;
      if (!processedHash.startsWith('0x')) {
        processedHash = `0x${processedHash}`;
      }
      
      const count = await store.dispatch('getHistoryCount', processedHash);
      historyCount.value = count;
      
      // 如果有历史记录，加载最新一条
      if (count > 0) {
        currentVersionIndex.value = count - 1; // 从最新的版本开始
        await fetchHistoryVersion(currentVersionIndex.value);
      }
    };
    
    // 获取特定版本的历史记录
    const fetchHistoryVersion = async (index) => {
      if (index < 0 || index >= historyCount.value) return;
      
      // 预处理数据哈希，确保格式正确
      let processedHash = props.dataHash;
      if (!processedHash.startsWith('0x')) {
        processedHash = `0x${processedHash}`;
      }
      
      const versionData = await store.dispatch('getHistoryAt', {
        dataHash: processedHash,
        index: index
      });
      
      if (versionData) {
        currentVersion.value = versionData;
      }
    };
    
    // 加载上一个版本
    const loadPreviousVersion = async () => {
      if (currentVersionIndex.value > 0) {
        currentVersionIndex.value--;
        await fetchHistoryVersion(currentVersionIndex.value);
      }
    };
    
    // 加载下一个版本
    const loadNextVersion = async () => {
      if (currentVersionIndex.value < historyCount.value - 1) {
        currentVersionIndex.value++;
        await fetchHistoryVersion(currentVersionIndex.value);
      }
    };
    
    // 当dataHash变化时重新加载数据
    watch(() => props.dataHash, () => {
      fetchHistoryCount();
    });
    
    // 组件挂载时加载数据
    onMounted(fetchHistoryCount);
    
    return {
      historyCount,
      currentVersionIndex,
      currentVersion,
      loading,
      error,
      loadPreviousVersion,
      loadNextVersion
    };
  }
}
</script>

<style scoped>
.card {
  margin-bottom: 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.badge {
  font-size: 0.9rem;
  padding: 0.4rem 0.8rem;
}
</style> 